package com.pri.chat.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.net.ParseException;
import android.os.Build;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.netease.nim.uikit.common.util.string.StringUtil;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.MainActivity;
import com.pri.chat.R;
import com.pri.chat.base.BaseActivity;
import com.pri.chat.base.TcWebActivity;
import com.pri.chat.model.CodeModel;
import com.pri.chat.model.JsonBean;
import com.pri.chat.model.RegModel;
import com.pri.chat.utils.Auth;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.LocationUtil;
import com.pri.chat.utils.PictureChoiceUtil;
import com.pri.chat.utils.StringUtils;
import com.pri.chat.utils.TimeUtils;
import com.pri.chat.view.ImageViewPlus;
import com.pri.chat.view.XRadioGroup;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.vondear.rxtool.RxDeviceTool;
import com.vondear.rxtool.view.RxToast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

import androidx.annotation.Nullable;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：添加类的描述
 *
 * @author wx5e48d604c2885118
 * @time 2020/4/15
 */
public class RegActivity extends BaseActivity {
    private static final String TAG = "RegActivity";
    @BindView(R.id.et_login_name)
    EditText etLoginName;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.tv_code)
    TextView tvCode;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.cb_xieyi)
    CheckBox cbXieyi;
    @BindView(R.id.tv_xieyi)
    TextView tvXieyi;
    @BindView(R.id.tv_ys)
    TextView tvYs;
    @BindView(R.id.tv_reg)
    TextView tvReg;
    @BindView(R.id.iv_tou)
    ImageViewPlus ivTou;
    @BindView(R.id.rb_man)
    LinearLayout rbMan;
    @BindView(R.id.rb_woman)
    LinearLayout rbWoman;
    @BindView(R.id.xg_sex)
    XRadioGroup xgSex;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_yqm)
    EditText et_yqm;

    @BindView(R.id.registerLinear1)
    View registerLinear1;
    @BindView(R.id.tv_next)
    View tv_next;
    @BindView(R.id.registerLinear2)
    View registerLinear2;

    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.et_birthday)
    TextView et_birthday;
    @BindView(R.id.et_city)
    TextView et_city;

    @BindView(R.id.mmLinear)
    View mmLinear;




    private boolean isFinish = false;
    private TimeCount time;
    private UploadManager uploadManager = new UploadManager();
    private String mCodeId;//验证码ID
    private RegModel regModel = new RegModel();//注册上传参数


    private String openId;
    private String headPic;
    private String ncName;
    private String yqmCode;


    @Override
    protected void onDestroy() {
        super.onDestroy();
        isFinish = true;
        if(time != null){
            time.cancel();
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_reg_layout;
    }

    public static String city = "";
    private LocationUtil locationUtil;

    private void initLoc() {
        locationUtil = new LocationUtil(this);
        locationUtil.dingwei();
        locationUtil.setOnLocChangedListener(new LocationUtil.OnLocChangedListener() {
            @Override
            public void onLocationChanged(AMapLocation loc) {
                if(!StringUtils.isEmpty(loc.getCity())){
                    Log.i("城市：", loc.getCity());
                    if(StringUtils.isEmpty(et_city.getText().toString())){
                        et_city.setText(loc.getCity());
                    }
                }
                locationUtil.stopLocation();
                locationUtil.destroyLocation();
            }
        });
    }

    TimePickerView mStartDatePickerView;

    /**
     * 初始化开始日期选择器控件
     */
    private void initStartTimePicker() {
        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Calendar selectedDate = TimeUtils.strToCalendar(StringUtils.isEmpty(et_birthday.getText().toString())?TimeUtils.getCurrentTime():et_birthday.getText().toString());
        //设置最小日期和最大日期
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();//最大日期是今天
        try {
            startDate.setTime(TimeUtils.strToDate("1970-01-01"));//设置为2006年4月28日
            endDate.setTime(TimeUtils.strToDate(TimeUtils.getCurrentTime()));//设置为2006年4月28日
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //时间选择器
        mStartDatePickerView = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
                et_birthday.setText(TimeUtils.dataToStr(date, "yyyy-MM-dd"));
            }
        })
//                .setDecorView((RelativeLayout)findViewById(R.id.activity_rootview))//必须是RelativeLayout，不设置setDecorView的话，底部虚拟导航栏会显示在弹出的选择器区域
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("", "", "", "", "", "")
                .isCenterLabel(false)//是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setTitleText("选择出生日期")//标题文字
                .setTitleSize(20)//标题文字大小
                .setTitleColor(getResources().getColor(R.color.color_333333))//标题文字颜色
                .setCancelText("取消")//取消按钮文字
                .setCancelColor(getResources().getColor(R.color.color_666666))//取消按钮文字颜色
                .setSubmitText("确定")//确认按钮文字
                .setSubmitColor(getResources().getColor(R.color.orange))//确定按钮文字颜色
                .setContentTextSize(20)//滚轮文字大小
                .setTextColorCenter(getResources().getColor(R.color.orange))//设置选中文本的颜色值
                .setLineSpacingMultiplier(1.8f)//行间距
                .setDividerColor(getResources().getColor(R.color.gray))//设置分割线的颜色
                .setRangDate(startDate, endDate)//设置最小和最大日期
                .setDate(selectedDate)//设置选中的日期
                .build();
    }

    @Override
    protected void initView() {
        initLoc();
        initStartTimePicker();
        initJsonData();
        openId = getIntent().getExtras().getString("openId");
        headPic = getIntent().getExtras().getString("headPic");
        ncName = getIntent().getExtras().getString("ncName");
        if (StringUtil.isEmpty(openId)) {
            registerLinear1.setVisibility(View.VISIBLE);
            registerLinear2.setVisibility(View.GONE);
            mmLinear.setVisibility(View.VISIBLE);
            time = new TimeCount(60000, 1000);
        } else {
            registerLinear1.setVisibility(View.GONE);
            registerLinear2.setVisibility(View.VISIBLE);
            mmLinear.setVisibility(View.GONE);
            etName.setText(ncName);
            RequestOptions options = new RequestOptions()
                    .placeholder(R.mipmap.ic_paizhao_img)//图片加载出来前，显示的图片
                    .fallback(R.mipmap.ic_paizhao_img) //url为空的时候,显示的图片
                    .error(R.mipmap.ic_paizhao_img);//图片加载失败后，显示的图片
            Glide.with(mContext).load(headPic).apply(options).into(ivTou);
            regModel.setHeadPic(headPic);
        }
        yqmCode = SharedHelper.readValueByKeyForString(this,"yqmCode");
        et_yqm.setText(yqmCode);
    }

    @Override
    protected void initData() {

    }

    private String locationPath;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                // 图片选择结果回调
                if (!PictureSelector.obtainMultipleResult(data).isEmpty()) {
                    locationPath = PictureSelector.obtainMultipleResult(data).get(0).getPath();
                    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        locationPath = PictureSelector.obtainMultipleResult(data).get(0).getAndroidQToPath();
                    }
                    RequestOptions options = new RequestOptions()
                            .placeholder(R.mipmap.ic_paizhao_img)//图片加载出来前，显示的图片
                            .fallback(R.mipmap.ic_paizhao_img) //url为空的时候,显示的图片
                            .error(R.mipmap.ic_paizhao_img);//图片加载失败后，显示的图片
                    Glide.with(mContext).load(locationPath).apply(options).into(ivTou);
                }
                break;
        }
    }

    private void uploadImg(String data) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String key = "img_" + sdf.format(new Date());
        String token = "ayjstx";
        uploadManager.put(data, key, Auth.create(HttpMethods.ACCESS_KEY, HttpMethods.SECRET_KEY).uploadToken(token),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        if (info.isOK()) {
                            Log.i("qiniu", "Upload Success");
                            Log.d(TAG, "complete: " + HttpMethods.QN_PATH + key);
                            regModel.setHeadPic(HttpMethods.QN_PATH + key);
                            login();
                        } else {
                            Log.i("qiniu", "Upload Fail");
                            //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                        }
                        Log.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                    }
                }, null);
    }


    @OnClick({R.id.rb_man,R.id.rb_woman,R.id.tv_next, R.id.tv_code, R.id.tv_xieyi, R.id.tv_ys, R.id.tv_reg, R.id.iv_tou, R.id.et_birthday, R.id.et_city})
    public void onViewClicked(View view) {
        String mobile = etLoginName.getText().toString();
        String code = etCode.getText().toString();
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.rb_man:
                regModel.setSex("男");
                rbMan.setBackgroundResource(R.drawable.btn_sex_man);
                rbWoman.setBackgroundResource(R.drawable.btn_gray_20_shape);
                break;
            case R.id.rb_woman:
                regModel.setSex("女");
                rbWoman.setBackgroundResource(R.drawable.btn_sex_woman);
                rbMan.setBackgroundResource(R.drawable.btn_gray_20_shape);
                break;
            case R.id.et_city:
                showPickerView();
                break;
            case R.id.et_birthday:
                mStartDatePickerView.show();
                break;
            case R.id.tv_next:
                //校验验证码
                if (mobile.isEmpty()) {
                    RxToast.normal(getString(R.string.login_mobile_empty));
                    return;
                }
                if (code.isEmpty()) {
                    RxToast.normal(getString(R.string.login_code_empty));
                    return;
                }
                checkCode();
                break;
            case R.id.tv_code:
                if (mobile.isEmpty()) {
                    RxToast.normal("手机号为空");
                } else {
                    sendCode(mobile);
                }
                break;
            case R.id.iv_tou:
                PictureChoiceUtil.getInstance().choiceTouPic(this, new ArrayList<>());
                break;
            case R.id.tv_xieyi:
                intent.setClass(this, TcWebActivity.class);
                intent.putExtra("title", "用户协议");
                intent.putExtra("url", HttpMethods.BASE_URL + "p/front_editorHtmlShow.html?code=yonghuxieyiCode");
                startActivity(intent);
                break;
            case R.id.tv_ys:
                intent.setClass(this, TcWebActivity.class);
                intent.putExtra("title", "隐私协议");
                intent.putExtra("url", HttpMethods.BASE_URL + "p/front_editorHtmlShow.html?code=yinsixieyiCode");
                startActivity(intent);
                break;
            case R.id.tv_reg:
                if (isNull(etName)) {
                    RxToast.normal("请编辑您的昵称");
                    return;
                }
                if (StringUtil.isEmpty(openId)) {
                    if (isNull(etPwd)) {
                        RxToast.normal(etPwd.getHint().toString());
                        return;
                    }
                }

                if (isNull(et_birthday)) {
                    RxToast.normal(et_birthday.getHint().toString());
                    return;
                }

                if (isNull(regModel.getSex())) {
                    RxToast.normal("请选择性别");
                    return;
                }

                if (!cbXieyi.isChecked()) {
                    RxToast.normal("请阅读并勾选用户协议");
                    return;
                } else {
                    if(!StringUtils.isEmpty(locationPath)){
                        showProgressDialog();
                        uploadImg(locationPath);
                    }else{
                        if(StringUtils.isEmpty(regModel.getHeadPic())){
                            if (StringUtils.isEmpty(locationPath)) {
                                RxToast.normal("请上传图像！");
                                return;
                            }
                        }else{
                            login();
                        }
                    }
                }
                break;
        }
    }



    private ArrayList<JsonBean> options1Items = new ArrayList<>(); //省
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();//市
    private int opt1 = -1, opt2 = -1;

    private void showPickerView() {// 弹出选择器（省市区三级联动）
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                et_city.setText(options2Items.get(options1).get(options2));
                opt1 = options1;
                opt2 = options2;

            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(mContext.getResources().getColor(R.color.orange)) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();
        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items);//三级选择器
        if (opt1 != -1) {
            pvOptions.setSelectOptions(opt1, opt2);
        }
        pvOptions.show();
    }
    public String getJson(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    private void initJsonData() {//解析数据 （省市区三级联动）
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         * */
        String JsonData = getJson(this, "province.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        /**
         * 添加省份数据
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三级）
            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }
            /**
             * 添加城市数据
             */
            options2Items.add(CityList);
        }
    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }



    /**
     * 发送验证码
     *
     * @param mobile 手机号
     */
    private void sendCode(String mobile) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            Log.d(TAG, "onNext: " + baseBean.toString());
            mCodeId = (String) baseBean.getData();
            time.start();
            RxToast.normal("验证码发送成功");
        };
        CodeModel codeModel = new CodeModel(mobile, 0);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(codeModel));
        HttpMethods.getInstance().sendCode(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }


    /**
     * 发送验证码
     */
    private void checkCode() {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            registerLinear1.setVisibility(View.GONE);
            registerLinear2.setVisibility(View.VISIBLE);
        };
        RegModel rg = new RegModel();
        rg.setCode(etCode.getText().toString());
        rg.setSendId(mCodeId);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(rg));
        HttpMethods.getInstance().checkCode(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }

    private void login() {
        String deviceId = RxDeviceTool.getIMEI(this);
        if (StringUtils.isEmpty(deviceId)) {
            RxToast.normal("没有获取到设备ID，无法注册！");
            return;
        }
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            dismissProgressDialog();
            Log.d(TAG, "onNext: " + baseBean.toString());
            RxToast.normal("注册成功");
            if (!StringUtil.isEmpty(openId)) {
                setResult(Activity.RESULT_OK);
            }else{
                Intent intent = new Intent();
                intent.putExtra("mobile",regModel.getMobile());
                intent.putExtra("password",regModel.getPassword());
                setResult(Activity.RESULT_OK,intent);
            }
            finish();
        };

        String mobile = etLoginName.getText().toString();
        String code = etCode.getText().toString();
        regModel.setCode(code);
        regModel.setMobile(mobile);
        regModel.setNcName(getString(etName));
        regModel.setSendId(mCodeId);
        regModel.setPassword(getString(etPwd));
        regModel.setDeviceId(deviceId);  //new Random().nextInt(100)
        regModel.setOpenid(openId);
        regModel.setBirthday(getString(et_birthday));
        regModel.setCity(getString(et_city));
        regModel.setInvitedUserCode(et_yqm.getText().toString());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(regModel));

        if (StringUtil.isEmpty(openId)) {
            HttpMethods.getInstance().registerNew(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
        } else {
            HttpMethods.getInstance().registerWeChatNew(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
        }

    }


    class TimeCount extends CountDownTimer {

        TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {

            tvCode.setClickable(false);
            tvCode.setText(millisUntilFinished / 1000 + "秒");
        }

        @Override
        public void onFinish() {
            if (!isFinish) {
                tvCode.setText("重新获取");
                tvCode.setClickable(true);
            }


        }
    }
}
